package com.gree.flowable.app.tools.utils;

import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author ：180849
 * @date ：Created in 2021/5/10 15:51
 * @description：导出FormExcel的工具类
 * @modified By：
 * @version: 1.0
 */
public class ExcelExportUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExcelExportUtil.class);

    public static ResponseEntity<byte[]> exportExcelUtil(List<Map<String,String>> columnVOList,String excelName,String formId) throws Exception {
        logger.info(">>>>>>>>>>开始导出excel,进行数据整理>>>>>>>>>>");


        logger.info(">>>>>>>>>>开始导出excel,结束数据整理>>>>>>>>>>");
        return BaseFrontController.buildResponseEntity(export(columnVOList),excelName+".xlsx");

    }

    public static InputStream export(List<Map<String,String>> columnList){
        logger.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream = null;
        SXSSFWorkbook wb = new SXSSFWorkbook ();
        SXSSFSheet sheet = wb.createSheet();
        if (columnList != null && columnList.size() > 0){
            logger.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            SXSSFRow row = sheet.createRow(0);
            for (int i = 0; i < columnList.size(); i++) {
                Map<String, String> columnMap = columnList.get(i);
                SXSSFCell cell = row.createCell(i);
                //设置每一列字段名
                cell.setCellValue(columnMap.get("name"));
            }
            logger.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }
        output = new ByteArrayOutputStream();
        try {
            wb.write(output);
            inputStream = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (output != null) {
                    output.close();
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>结束导出方法>>>>>>>>>>");
        return inputStream;
    }
}
